package cn.umbrella.crm_core;

import cn.umbrella.crm_core.workbench.domain.Activity;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 用于处理读取市场活动的监听器
 */
@Slf4j
public class ActivityReadListener implements ReadListener<Activity> {

    // 限制一次读取的数量，最大100
    private static final int BATCH_COUNT = 100;
    // 定义缓存
    private List<Activity> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    public void invoke(Activity activity, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", JSON.toJSONString(activity));
        cachedDataList.add(activity);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData(cachedDataList);
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData(cachedDataList);
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData(List<Activity> cachedDataList) {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        for (Activity activity : cachedDataList) {
            System.out.println(activity.toString());
        }
        log.info("存储数据库成功！");
    }
}
